/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
(function () {
    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        mode: 'text/x-plsql',
        lineNumbers: true,
        vimMode: true,
        styleActiveLine: true,
        theme: 'eclipse',
        tabSize: 3,
        autofocus: true,
        extraKeys: {
            'Ctrl-J': 'autocomplete',
            'F2': function (cm) {
                cm.setOption("fullScreen", !cm.getOption("fullScreen"));
            },
            'F3': function (cm) {
                cm.setValue('');
            },
            'F9': function (cm) {
                showMessage();
                var text = cm.getSelection() || cm.getValue();
                if (!text.replace(/^\s+|\s+$/, '')) {
                    return;
                }

                var se = cm.getSelection();
                if (!cm.getSelection()) {
                    editor.setSelection({
                        line: 0,
                        ch: 0
                    }, {
                        line: cm.lineCount(),
                        ch: cm.getLine(cm.lineCount() - 1).length
                    });
                }
                cm.setOption('readOnly', true);

                $.ajax('database/execute', {
                    data: {
                        sql: text
                    },
                    dataType: 'json',
                    success: function (data, textStatus, jqXHR) {
                        if (data.count > -1) {
                            showMessage(Date.now() + ':' + data.count + '条受影响' + ", " + data.msg);
                        } else if (data.result) {
                            showData(data.result);
                        } else {
                            showMessage(data.msg);
                        }
                        editor.setOption('readOnly', false);
                        if (se) {
                            editor.setSelection(se);
                        }
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        editor.setOption('readOnly', false);
                        if (se) {
                            editor.setSelection(se);
                        }
                        alert(errorThrown);
                    }
                });
            }
        }
    });

    var editMode = document.getElementById("edit-mode");
    editMode.onchange = function () {
        editor.setOption("keyMap", editMode.value || 'default');
    }

    //当有横向滚动条时，需要此js，时内容滚动头部也能滚动。
    $('.fix-table-body').scroll(onTableScroll);
    $(window).resize(fixTable);
    $(document).ready(fixTable);

    //
    $('li a').bind('click', function () {
        $(this).siblings('ul').toggle()
    });

    function showMessage(msg) {
        var rs = $('#result'),
            width = rs.width(),
            height = rs.height(),
            msg = msg || 'Executing... ';

        $('#msg').html(msg).css({
            'position': 'absolute',
            'top': 0,
            'width': width + 'px',
            'height': height + 'px',
            'padding': '5px',
            'background': '#FFF'
        }).show();
    }

    function showData(data) {
        var cols = data[0].length,
            rows = data.length - 1,
            header = $("#result .fix-table-head thead"),
            body = $('#result .fix-table-body tbody'),
            row = 0,
            col = 0,
            tr = $("<tr>");

        header.html(''), body.html('');
        $('#result .fix-table-head table').css('width', 'auto');
        $('#result .fix-table-body table').css('width', 'auto');

        // header
        $('<th>').html('').appendTo(tr);
        for (; col < cols; col++) {
            $("<th>").html(data[0][col]).appendTo(tr);
        }
        tr.appendTo(header);

        // body
        for (; row < rows; row++) {
            tr = $("<tr>");
            $('<td>').html(row + 1).appendTo(tr);   // line num
            for (col = 0; col < cols; col++) {
                $("<td>").html(data[row + 1][col]).appendTo(tr);
            }
            tr.appendTo(body);
        }

        hideLoader();
        fixTable();
    }

    function hideLoader() {
        $("#msg").hide();
    }

    function showLoader() {
        $('#msg').show();
    }

    function onTableScroll() {
        $('.fix-table-head table').css('margin-left', -($('.fix-table-body').scrollLeft()));
    }

    // 修正头部与内容对应列宽度
    function fixTable() {
        var theadOffset = $('.fix-table-head>table').width(),
            tbodyOffset = $('.fix-table-body>table').width(),
            totalWidth = 0,
            tdCount = $('.fix-table-body>table>tbody>tr:last').find('td:last').index() + 1,
            index = 0, maxWidth = 0, th, td;

        for (; index < tdCount; index++) {
            th = $('.fix-table-head th').eq(index);
            td = $('.fix-table-body>table>tbody>tr:last').find('td').eq(index);
            maxWidth = Math.max(th.width(), td.width());

            theadOffset -= th.width();
            tbodyOffset -= td.width();
            totalWidth += maxWidth;

            th.css('width', maxWidth);
            td.css('width', maxWidth);
        }

        $('.fix-table-head>table').css('width', totalWidth + theadOffset);
        $('.fix-table-body>table').css('width', totalWidth + tbodyOffset);
    }
})();
